<?php
/**
 * SocialEngine
 *
 * @category   Application_Extensions
 * @package    Page
 * @copyright  Copyright Hire-Experts LLC
 * @license    http://www.hire-experts.com
 * @version    $Id: IndexController.php 2010-08-31 16:05 idris $
 * @author     Idris
 */

/**
 * @category   Application_Extensions
 * @package    Page
 * @copyright  Copyright Hire-Experts LLC
 * @license    http://www.hire-experts.com
 */

class Page_IndexController extends Core_Controller_Action_Standard
{
	public function init() 
  {	 
  	$content = $this->_getParam('content', '');
		$content_id = $this->_getParam('content_id', 0);
  	
    $subject = null;
    if( !Engine_Api::_()->core()->hasSubject() )
    {
      $id = $this->_getParam('id', $this->_getParam('page_id'));
      if( null !== $id )
      {
        $subject = Engine_Api::_()->page()->getPage($id);
        if( $subject && $subject->getIdentity() )
        {
        	$subject->setContentInfo($content, $content_id);
          Engine_Api::_()->core()->setSubject($subject);
        }
      }
    }
  }

  public function createAction()
  {
    if( !$this->_helper->requireAuth()->setAuthParams('page', null, 'create')->isValid() ) return;
    
  	$this->view->navigation = $navigation = $this->getNavigation();
      
    $table = $this->_helper->api()->getDbtable('pages', 'page');
    $page = $table->createRow();
    	
    $page_id = $table->lastInsertId();
    
    $page->page_id = $page_id;
    $page->setIdentity($page_id);

  	$aliasedFields = $page->fields()->getFieldsObjectsByAlias();
		$this->view->topLevelId = $topLevelId = 0;
    $this->view->topLevelValue = $topLevelValue = null;

		if( isset($aliasedFields['profile_type']) ) {
      $aliasedFieldValue = $aliasedFields['profile_type']->getValue($page);
      $topLevelId = $aliasedFields['profile_type']->field_id;
      $topLevelValue = ( is_object($aliasedFieldValue) ? $aliasedFieldValue->value : null );
      if( !$topLevelId || !$topLevelValue ) {
        $topLevelId = null;
        $topLevelValue = null;
      }
      $this->view->topLevelId = $topLevelId;
      $this->view->topLevelValue = $topLevelValue;
    }
    
    $parent_type = $this->getRequest()->getParam('parent_type', 'user');
    $subject_id = $this->getRequest()->getParam('subject_id', Engine_Api::_()->user()->getViewer()->getIdentity());
    
    $this->view->form = $form = new Page_Form_Create(array('item' => $page,'topLevelId' => $topLevelId,'topLevelValue' => $topLevelValue, 
    	'parent_type' => 'user', 'parent_id' => $subject_id));
    
    if( !$this->getRequest()->isPost() ){
      return;
    }
    
   	$values = $this->getRequest()->getPost();
   	$extra = $values['extra'];
   	
   	if (!$form->isValid($values)){
   		$form->populate($values);
   		return ;
   	}
   	
    if ($table->checkUrl($extra['url'])){
    	$form->populate($values);
      $form->addError(Zend_Registry::get('Zend_Translate')->_('This URL is already taken by other page.'));
      return ;
    }
   	
   	$extra['url'] = strtolower(trim($extra['url']));
		$extra['url'] = preg_replace('/[^a-z0-9-]/', '-', $extra['url']);
		$extra['url'] = preg_replace('/-+/', "-", $extra['url']);
    
    $db = Engine_Api::_()->getDbtable('pages', 'page')->getAdapter();
    $db->beginTransaction();
    
    try
    {
	    $form->saveValues();
	    $viewer = $this->_helper->api()->user()->getViewer();
	    
	    $extra['user_id'] = $viewer->getIdentity();
	    $extra['parent_type'] = $this->getRequest()->getParam('parent_type', 'user');
	    $extra['parent_id'] =  $this->getRequest()->getParam('subject_id', $viewer->getIdentity());
    
    	$raw_tags = preg_split('/[,]+/', $extra['tags']);
    	$tags = array();
    	foreach ($raw_tags as $tag){
    		$tag = trim(strip_tags($tag));
    		if ($tag == ""){
    			continue ;
    		}
    		$tags[] = $tag;
    	}
			$page->tags()->addTagMaps($viewer, $tags);
			unset($extra['tags']);

      $settings = Engine_Api::_()->getApi('settings', 'core');

//			$extra['description'] = utf8_encode($extra['description']);
//			$extra['title'] = utf8_encode($extra['title']);
			
    	$page->setFromArray($extra);
      $page->displayname = $page->title;
      $page->name = $page->url;
      $page->keywords = $extra['tags'];
      $page->approved = $settings->getSetting('page.approval', 1);
      
      $page->save();
      
      $page->membership()->addMember($viewer)->setUserApproved($viewer)->setResourceApproved($viewer);
      $page->getTeamList()->add($viewer);
      
    	if( !$_FILES['photo']['error'] ) {
        $page->setPhoto($form->getSubForm('extra')->photo);
      }
      
      $availableLabels = array(
        'everyone' => 'Everyone',
        'registered' => 'Registered Members',
        'likes' => 'Likes, Admins and Owner',
        'team' => 'Admins and Owner Only'
      );
    
      $view_options = (array) Engine_Api::_()->authorization()->getAdapter('levels')->getAllowed('page', $viewer, 'auth_view');
      $view_options = array_intersect_key($availableLabels, array_flip($view_options));
      
      $comment_options = (array) Engine_Api::_()->authorization()->getAdapter('levels')->getAllowed('page', $viewer, 'auth_comment');
      $comment_options = array_intersect_key($availableLabels, array_flip($comment_options));
      
      $posting_options = (array) Engine_Api::_()->authorization()->getAdapter('levels')->getAllowed('page', $viewer, 'auth_posting');
      $posting_options = array_intersect_key($availableLabels, array_flip($posting_options));
      
      $values = array('auth_view' => key($view_options), 'auth_comment' => key($comment_options), 'auth_posting' => key($posting_options));
      $page->setPrivacy($values);
      $page->createContent();
			
			$activityApi = Engine_Api::_()->getDbtable('actions', 'activity');
      $action = $activityApi->addActivity($viewer, $page, 'page_create');
//      $activityApi->attachActivity($action, $page);
      
      Engine_Api::_()->like()->manageLikeClub($page, 1);
      
      $db->commit();
    }
  	catch( Engine_Image_Exception $e )
    {
      $db->rollBack();
      $form->addError(Zend_Registry::get('Zend_Translate')->_('The image you selected was too large.'));
    }
  	catch( Exception $e )
    {
      $db->rollBack();
      throw $e;
    }
    
    $this->_redirectCustom(array('route' => 'page_team', 'action' => 'edit', 'page_id' => $page->page_id));
		return ;
  }
  
  public function validateAction()
  {
  	if( !$this->_helper->requireUser()->isValid() || !$this->_helper->requireAuth()->setAuthParams('page', null, 'create')->checkRequire() ) {
  		return;
  	}
  	
  	$url = $this->_getParam('url');
  	
  	$url = strtolower(trim($url));
		$url = preg_replace('/[^a-z0-9-]/', '-', $url);
		$url = preg_replace('/-+/', "-", $url);
  	
  	$table = Engine_Api::_()->getDbTable('pages', 'page');
    
  	if ($table->checkUrl($url)){
  		$this->view->success = 0;
  		$this->view->message = Zend_Registry::get('Zend_Translate')->_("Page with this url is already exists.");
  	}else{
  		$this->view->success = 1;
  		$this->view->message = Zend_Registry::get('Zend_Translate')->_("This url is free.");
  	}
    
  	return;
  }
  
  public function getNavigation()
  {
    $navigation = new Zend_Navigation();
    $navigation->addPages(array(
      array(
        'label' => "Pages",
        'route' => 'page_browse',
        'action' => 'index'
      )));

    $viewer = Engine_Api::_()->user()->getViewer();
    
    if ($viewer->getIdentity()) {
      $navigation->addPage(array(
          'label' => 'My Pages',
          'route'=> 'page_manage',
          'action' => 'manage'
        ));
        
      if( Engine_Api::_()->authorization()->isAllowed('page', null, 'create')){
        $navigation->addPage(array(
          'label' => 'Create New Page',
          'route' => 'page_create',
          'action' => 'create'
        ));
      }
    }
    
    return $navigation;
  }
    
  public function indexAction()
  {
		$page_num = $this->_getParam('page', 1);
  	$format = $this->_getParam('format');
  	$table = Engine_Api::_()->getDbTable('pages', 'page');
  	$settings = Engine_Api::_()->getApi('settings', 'core');
  	
  	if ($format != 'json'){
	    $this->view->tags = Engine_Api::_()->page()->getTags();
	    $this->view->popularLocations = Engine_Api::_()->page()->getPopularLocations();
	    $this->view->popularCategories = Engine_Api::_()->page()->getPopularCategories();
	    $this->view->viewer = Engine_Api::_()->user()->getViewer();
  	}
    
    $this->view->filterForm = $filterForm = new Page_Form_Search(array('type' => 'page'));
    $ipp = $settings->getSetting('page.browse_count', 10);
    $params = array('page' => $page_num, 'ipp' => $ipp, 'view' => 'map', 'search' => 1, 'sort' => 'newest', 'approved' => 1);
  	if( $this->getRequest()->isPost() && $format == 'json' ){
  		$options = $this->_getAllParams();
	  	if( !$filterForm->isValid($options) ){
	      $this->view->error = true;
	      return false;
	    }
	    
      $params['keyword'] = $options['extra']['keyword'];
      $params['sort'] = $options['extra']['sort'];
      $params['city'] = $options['extra']['city'];
      $params['tag_id'] = $options['extra']['tag_id'];
      $options = $filterForm->getValues();
      
      unset($options['extra']);
      unset($options['submit']);
      
      $params['fields'] = $options;
    }
    
    $this->view->params = $params;
    $this->view->page_num = $page_num;
    $this->view->paginator = $paginator = $table->getPaginator($params);
    $this->view->count = $paginator->getTotalItemCount();
    
		$this->view->markers = $markers = Engine_Api::_()->getApi('gmap', 'page')->getMarkers($paginator);
		$this->view->bounds = $bounds = Engine_Api::_()->getApi('gmap', 'page')->getMapBounds($markers);
		$this->view->field_ids = $field_ids = json_encode(Engine_Api::_()->page()->getCategorizedFieldIds());
		       
		$page_ids = array();
		foreach ($paginator as $page){
			$page_ids[] = $page->getIdentity();
		}
		
		$this->view->page_tags = Engine_Api::_()->page()->getPageTags($page_ids);
		
		if (Engine_Api::_()->getDbTable('modules', 'core')->isModuleEnabled('like')){
		  $this->view->page_likes = Engine_Api::_()->like()->getLikesCount('page', $page_ids);
		}
		
		if ($format == 'json'){
			$this->view->html = $this->view->render('index/browse.tpl');
		}else{
		  $this->view->gmap_js = Engine_Api::_()->getApi('gmap', 'page')->getMapJS();
			$this->view->markers = (!empty($markers)) ? json_encode($markers) : '';
			$this->view->bounds = json_encode($bounds);
		}
		
		$this->view->navigation = $navigation = $this->getNavigation();
  }
  
  public function manageAction()
  {
  	if ( !$this->_helper->requireUser->isValid() ) return ;
  	
  	$this->view->navigation = $navigation = $this->getNavigation();
  	
    $viewer = $this->_helper->api()->user()->getViewer();
    $table = $this->_helper->api()->getDbtable('pages', 'page');
    
    $select = $table->select();
    $select->where('user_id = ?', $viewer->getIdentity());
    $this->view->owner = $owner = Engine_Api::_()->user()->getViewer();
    
    $this->view->paginator = $paginator = Zend_Paginator::factory($select);
    
    $settings = Engine_Api::_()->getApi('settings', 'core');
    $ipp = $settings->getSetting('page.browse_count', 10);
    
    $paginator->setItemCountPerPage($ipp);
    $paginator->setCurrentPageNumber($this->_getParam('page'));
  }
	
	public function viewAction() 
	{
		$page = $this->_getParam('page', $this->_getParam('page_id'));
		
		if ($page == null){
			$this->_redirectCustom(array('route' => 'page_browse'));
  		return ;
		}
		
		$pageTable = Engine_Api::_()->getDbTable('pages', 'page');
		$select = $pageTable->select()->where('url = ?', $page)->orWhere('page_id = ?', $page)->orWhere('name = ?', $page);
		$pageObject = $pageTable->fetchRow($select);
		
		if ($pageObject == null){
			$this->_redirectCustom(array('route' => 'page_browse'));
  		return ;
		}
		
//		$this->_helper->requireSubject('page');
		$viewer = Engine_Api::_()->user()->getViewer();
		
		if( !$this->_helper->requireSubject()->isValid() ) return;
    if( !$this->_helper->requireAuth()->setAuthParams($pageObject, $viewer, 'view')->isValid() ) return;
		
		$pageObject->viewPage();
		$pageObject->description = stripslashes($pageObject->description);
		
		$path = Zend_Controller_Front::getInstance()->getControllerDirectory('page');
    $path = dirname($path) . '/layouts';

		$layout = Zend_Layout::startMvc();
		$layout->setViewBasePath($path);
		
		$content = Engine_Content::getInstance();
		$contentTable = Engine_Api::_()->getDbtable('pages', 'page');
    $content->setStorage($contentTable);
		
		if (null !== $pageObject){

			$this->view->headTitle()->setAutoEscape(false);
			$this->view->headMeta()->setAutoEscape(false);

//			if( !empty($pageObject->title) ) {
//        $this->view->headTitle($pageObject->getTitle());
//      }
//
//      if( !empty($pageObject->description) ) {
//        $this->view->headMeta()->appendName('description', $pageObject->getDescription());
//      }

			$tags = $pageObject->tags()->getTagMaps();
			$tagString = '';
			foreach( $tags as $tagmap ){
				if( $tagString !== '' ) $tagString .= ', ';
				$tagString .= $tagmap->getTag()->getTitle();
			}

      if( !empty($tagString) ){
        $this->view->headMeta()->appendName('keywords', $tagString);
      }

      if( !empty($pageObject->layout) ){
        $this->_helper->layout->setLayout($pageObject->layout);
      }
      
      $this->_helper->content->setContentName($pageObject->getIdentity())->setEnabled();
			return;
		}
		
		throw new Zend_Controller_Exception(sprintf('Page %s does not exist', $page), 404);
	}
	
	public function largeMapAction() 
	{
		$page_id = $this->_getParam('page_id');
		
		if ($page_id === null){
			$this->view->result = 0;
			$this->view->message = Zend_Registry::get('Zend_Translate')->_("Undefined page.");
			return ;
		}
		
		$pageObject = Engine_Api::_()->getItem('page', $page_id);
		
		if(!$this->_helper->requireAuth()->setNoForward()->setAuthParams($pageObject, Engine_Api::_()->user()->getViewer(),'view')->checkRequire()){
			$this->view->result = 0;
      $this->view->message = Zend_Registry::get('Zend_Translate')->_("No rights");
      return;
		}
		
		$table = Engine_Api::_()->getDbTable('pages', 'page');
		$params = array('view' => 'map', 'page_id' => $page_id);
		$select = $table->getSelect($params);
    $this->view->page = $page = $table->fetchRow($select);
    $markers = array();
    
    if ($page->marker_id > 0){
	    $markers[0] = array(
				'marker_id' => $page->marker_id,
				'lat' => $page->latitude,
				'lng' => $page->longitude,
				'pages_id' => $page->page_id,
				'pages_photo' => $page->getPhotoUrl('thumb.normal'),
				'title' => $page->getTitle(),
				'desc' => substr($page->getDescription(),0,200),
	      'url' => $page->getHref()
			);
			
			$this->view->markers = json_encode($markers);
			$this->view->bounds = json_encode(Engine_Api::_()->getApi('gmap', 'page')->getMapBounds($markers));
    }
	}
	
}